package com.queen.testretrofitrxjava.presenter;

import android.support.annotation.NonNull;

import com.queen.testretrofitrxjava.entity.HttpResult;
import com.queen.testretrofitrxjava.entity.Subject;
import com.queen.testretrofitrxjava.http.HttpMethods;
import com.queen.testretrofitrxjava.httpSubscriber.ProgressSubscriber;
import com.queen.testretrofitrxjava.httpSubscriber.SubscriberOnNextListener;
import com.queen.testretrofitrxjava.presenter.presenterView.BasePresenterView;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import rx.functions.Action0;
import rx.subscriptions.Subscriptions;

/**
 * Created by liukun on 16/3/16.
 */
public class TopMoviePresenter {

    private SubscriberOnNextListener<HttpResult<List<Subject>>> getMovieOnNextListener;

    private List<Subject> movieArray;

    //当前的位置
    private int index = 0;
    //每页的数量
    private int pageSize = 10;
    //总长度
    private int movieTotalCount = 0;
    //是否正在加载
    private boolean isLoading = false;

    private BasePresenterView topMovieView;

    private HttpMethods httpMethods;

    @Inject
    public TopMoviePresenter(HttpMethods httpMethods) {

        movieArray = new ArrayList<>();

        getMovieOnNextListener = new SubscriberOnNextListener<HttpResult<List<Subject>>>() {
            @Override
            public void onNext(HttpResult<List<Subject>> httpResult) {

                movieTotalCount = httpResult.getTotal();
                index += pageSize;
                movieArray.addAll(httpResult.getSubjects());

                //获取数据之后，刷新view
                topMovieView.renderView(movieArray);
            }
        };
        this.httpMethods = httpMethods;

    }

    public void setView(@NonNull BasePresenterView topMovieView){
        this.topMovieView = topMovieView;
    }

    /**
     * 初始化UI
     */
    public void initialize() {
        requestTopMovieData();
    }

    public void getTopMovie(){
        if (index < movieTotalCount && !isLoading) {
            requestTopMovieData();
        }
    }

    public Subject getMovieByPosition(int position){
        return movieArray.get(position);
    }

    private void requestTopMovieData(){
        isLoading = true;

        ProgressSubscriber subscriber = new ProgressSubscriber(getMovieOnNextListener);
        subscriber.add(Subscriptions.create(new Action0() {
            @Override
            public void call() {
                isLoading = false;
            }
        }));

        httpMethods.getTopMovieHttpResult(subscriber, index, pageSize);
    }
}
